import h5Copy from '@/components/junyi-h5-copy/junyi-h5-copy.js'
export function copyText(e) {
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: e
	});
	// #endif
	// #ifdef H5
	const result = h5Copy(e)
	if (result === false) {
		uni.showToast({
			title: '不支持'
		})
	} else {
		uni.showToast({
			title: '复制成功',
			icon: 'none'
		})
	}
	// #endif
}
// 自定义长按事件
export function showImage(arr) {
	uni.previewImage({
		urls: arr,
		current: 0,
		longPressActions: {
			itemList: ['识别二维码', '保存图片'],
			success: function(res) {
				if (res.tapIndex == 0) {
					// 识别二维码
					uni.downloadFile({
						url: arr[0], //图片地址
						success: (res) => {
							if (res.statusCode === 200) {
								plus.barcode.scan(res.tempFilePath, function(type, code, file) {
									// #ifdef APP-PLUS
									if (plus.os.name == 'Android') {
										plus.runtime.openURL(encodeURI(code),
											function(res) {
												console.log(res)
											}
										)
									} else if (plus.os.name == 'iOS') {
										plus.runtime.openURL(encodeURI(code),
											function(res) {
												console.log(res)
											}
										)
									}
									// #endif
									// #ifdef H5
									window.location.href = url;
									// #endif
								}, function(error) {
									uni.showToast({
										title: '无法识别此图片',
										icon: 'none'
									})
								});
							} else {
								uni.showToast({
									title: '图片获取失败，请检查网络',
									icon: 'none'
								})
							}
						}
					})
				} else {
					// 保存图片
					// #ifdef H5
					plus.gallery.save(arr[0], function(e) {
						uni.showToast({
							title: '保存完成',
							icon: 'none',
							duration: 1000
						})
					}, function(e) {
						uni.showToast({
							title: '保存失败',
							icon: 'none',
							duration: 1000
						})
					});
					// #endif
					// #ifdef APP-PLUS
					uni.downloadFile({
						url: arr[0],
						success: (res) => {
							let file = res.tempFilePath;
							plus.gallery.save(file, function(e) {
								uni.showToast({
									title: '保存完成',
									icon: 'none',
									duration: 1000
								})
							}, function(e) {
								console.log(JSON.stringify(e))
								uni.showToast({
									title: '保存失败',
									icon: 'none',
									duration: 1000
								})
							});
						}
					});
					// #endif
				}

			},
			fail: function(res) {
				// console.log(res.errMsg);  
			}
		}
	});
}
// 自定义扫码
export function discernImage(url) {
	uni.downloadFile({
		url: url, //图片地址
		success: (res) => {
			if (res.statusCode === 200) {
				// uni.getImageInfo({
				// 	src: res.tempFilePath,
				// 	success(e) {
				// 		console.log(JSON.stringify(e))
				// 	},
				// 	fail() {

				// 	},
				// })
				plus.barcode.scan(res.tempFilePath, function(type, code, file) {
					console.log(type)
					// #ifdef APP-PLUS
					if (plus.os.name == 'Android') {
						plus.runtime.openURL(encodeURI(code),
							function(res) {
								console.log(res)
							}
						)
					} else if (plus.os.name == 'iOS') {
						plus.runtime.openURL(encodeURI(code),
							function(res) {
								console.log(res)
							}
						)
					}
					// #endif
					// #ifdef H5
					window.location.href = url;
					// #endif
				}, function(error) {
					console.log(JSON.stringify(error))
					uni.showToast({
						title: '无法识别此图片',
						icon: 'none'
					})
				});
			} else {
				uni.showToast({
					title: '图片获取失败，请检查网络',
					icon: 'none'
				})
			}
		}
	})
}

export function saveImg(url, type, callback) {
	// #ifdef APP-PLUS
	uni.downloadFile({
		url: url,
		success: (res) => {
			if (res.statusCode === 200) {
				let file = res.tempFilePath;
				uni.saveImageToPhotosAlbum({
					filePath: file,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: "none"
						});
						callback(res)
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: "none"
						});
						callback(res)
					},
				});
			}
		}
	});
	// #endif
	// #ifdef H5
	if (navigator.userAgent.indexOf('Html5Plus') == -1) {
		if (type == 1) {
			uni.showToast({
				title: '浏览器使用手机截屏保存',
				icon: "none"
			});
		} else {
			uni.showToast({
				title: '打开图片，长按图片保存',
				icon: "none"
			});
		}
	} else {
		if (url.indexOf('data:image/') == 0) {
			// 把图片转成base64
			var b = new plus.nativeObj.Bitmap();
			b.loadBase64Data(url);
			var fileType = url.indexOf('png') > -1 ? ".png" : ".jpeg";
			var fileName = new Date().getTime() + fileType;
			b.save('_www/' + fileName, {
				overwrite: true
			}, function() {
				plus.gallery.save('_www/' + fileName, function(e) {
					uni.showToast({
						title: '保存成功',
						icon: "none"
					});
				}, function(e) {
					uni.showToast({
						title: '保存图片失败',
						icon: "none"
					});
				});
			}, function(err) {
				uni.showToast({
					title: '保存图片失败',
					icon: "none"
				});
			});
			callback(1)
		} else {
			var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
				// 下载完成
				if (status == 200) {
					plus.gallery.save(d.filename, function(e) {
						uni.showToast({
							title: '保存成功',
							icon: "none"
						});
					}, function(e) {
						uni.showToast({
							title: '保存图片失败',
							icon: "none"
						});
					});
				} else {
					uni.showToast({
						title: '下载图片资源失败',
						icon: "none"
					});
				}
				callback(1)
			});
			dtask.start();
		}
	}
	// #endif
}

export function getParameterByName(name, url) {
	if (!url) url = location.href;
	name = name.replace(/[\[\]]/g, '\\$&');
	var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
		results = regex.exec(url);
	if (!results) return null;
	if (!results[2]) return '';
	return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

/**
 * javascript实现PHP字典排序
 * @param {Object} vm 当前this
 * @param {Array} inputArr 规定要进行排序的数组
 * @param {String} sort_flags 规定如何排列数组的元素/项目
 */
export function ksort(vm, inputArr, sort_flags) {
	var tmp_arr = {},
		keys = [],
		sorter, i, k, that = vm,
		strictForIn = false,
		populateArr = {};

	switch (sort_flags) {
		case 'SORT_STRING':
			// compare items as strings
			sorter = function(a, b) {
				return that.strnatcmp(a, b);
			};
			break;
		case 'SORT_LOCALE_STRING':
			// compare items as strings, original by the current locale (set with  i18n_loc_set_default() as of PHP6)
			var loc = vm.i18n_loc_get_default();
			sorter = vm.php_js.i18nLocales[loc].sorting;
			break;
		case 'SORT_NUMERIC':
			// compare items numerically
			sorter = function(a, b) {
				return ((a + 0) - (b + 0));
			};
			break;
			// case 'SORT_REGULAR': // compare items normally (don't change types)
		default:
			sorter = function(a, b) {
				var aFloat = parseFloat(a),
					bFloat = parseFloat(b),
					aNumeric = aFloat + '' === a,
					bNumeric = bFloat + '' === b;
				if (aNumeric && bNumeric) {
					return aFloat > bFloat ? 1 : aFloat < bFloat ? -1 : 0;
				} else if (aNumeric && !bNumeric) {
					return 1;
				} else if (!aNumeric && bNumeric) {
					return -1;
				}
				return a > b ? 1 : a < b ? -1 : 0;
			};
			break;
	}

	// Make a list of key names
	for (k in inputArr) {
		if (inputArr.hasOwnProperty(k)) {
			keys.push(k);
		}
	}
	keys.sort(sorter);

	// BEGIN REDUNDANT
	vm.php_js = vm.php_js || {};
	vm.php_js.ini = vm.php_js.ini || {};
	// END REDUNDANT
	strictForIn = vm.php_js.ini['phpjs.strictForIn'] && vm.php_js.ini['phpjs.strictForIn'].local_value && vm.php_js
		.ini['phpjs.strictForIn'].local_value !== 'off';
	populateArr = strictForIn ? inputArr : populateArr;

	// Rebuild array with sorted key names
	for (i = 0; i < keys.length; i++) {
		k = keys[i];
		tmp_arr[k] = inputArr[k];
		if (strictForIn) {
			delete inputArr[k];
		}
	}
	for (i in tmp_arr) {
		if (tmp_arr.hasOwnProperty(i)) {
			populateArr[i] = tmp_arr[i];
		}
	}

	return strictForIn || populateArr;
}

export function querySort(data) {
	let str = '';
	for (let key in data) {
		str += key + "=" + data[key] + "&"
	}
	str = str.substring(0, str.length - 1);
	return str;
}


//防抖 
export function Debounce(fn, delay) {
	let timer = null; //借助闭包
	return function() {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(fn, delay); // 简化写法
	};
}